/**************************************************************************************
*
*	Copyright (C) 2009-2010 Brent Andrew O. Chua - See LICENSE.txt for more info.
*		
*	Filename	-	FileIO.cpp
*
*	Comments	-	See FileIO.h
*
**************************************************************************************/

#include "FileIO.h"

////PSX_REGISTRY_OBJECT_START( FileIO, ERegistryPriority::Normal, ERegistryPriority::BelowNormal )
////	PSX_REGISTRY_ON_TEST()
////	{
////		int x = 0;
////	}

////PSX_REGISTRY_OBJECT_END()

bool FileIO::Open( const char *pFileName, FILEOP options )
{
	Close();

	m_fileOP = options;
	char mode[15];

	if ( (options & FILEOP_READ) && (options & FILEOP_WRITE) )
	{
		if ( options & FILEOP_TRUNCATE )
			sprintf( mode, ("w+") );
		else if ( options & FILEOP_APPENED )
			sprintf( mode, ("a+") );
		else
			sprintf( mode, ("r+") );		// File must exist
	}
	else if ( options & FILEOP_READ )
		sprintf( mode, ("r") );			// File must exist
	else if ( options & FILEOP_WRITE )
	{
		if ( options & FILEOP_APPENED )
			sprintf( mode, ("a") );
		else
			sprintf( mode, ("w") );
	}

	if ( options & FILEOP_BINARY )
		strcat( mode + strlen( mode ), ("b") );

#if defined( PSX_UNICODE )
	m_pFStream = _wfopen( pFileName, mode );
#else
	m_pFStream = fopen( pFileName, mode ); 
#endif /* defined( PSX_UNICODE ) */

	if ( !m_pFStream )
		return false;

	if ( options & FILEOP_GOTO_END )
		Seek( 0, SEEKOP_END );

	return true;
}

const char * FileIO::GetLine( string &str )
{
	char pBuffer[ 1024 ];
	char *pRet;
	unsigned int startSize = str.length();
	unsigned int newLength;

	str.clear();

	// We want to continue reading until we've reached a newline
	do {

		pRet = fgets( pBuffer, sizeof(pBuffer), m_pFStream );

		if ( pRet )
			str = str + pRet;
		else
			break;

		newLength = str.length();

	} while ( newLength && str[newLength  - 1] != '\n' );

	return startSize != newLength ? str.c_str() : NULL;
}